/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View, Image, ScrollView} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import {FcView} from "@/components/FcView";
import PageFormBtn from "@/components/PageFormBtn";
import TabCard from "@/components/TabCard";
import FormTitle from "@/components/FormTitle";
import FcButton from "@/components/FcButton";
import {aiOriginalityData} from "@/utils/data"
import {
    Flex,
    Button,
    List,
    Modal,
    Provider,
    Switch,
    Toast,
    WhiteSpace,
    WingBlank,
} from "@ant-design/react-native";
import RequiredIcon from "@/components/RequiredIcon";
import {LinearGradient} from "expo-linear-gradient";
import Slider from '@react-native-community/slider';
import FcSlider from "@/components/FcSlider";
import Animated, {useAnimatedRef} from "react-native-reanimated";
import FcModal from "@/components/FcModal";
import {useGetGroupTemplateListQuery} from "@/store/api/aiOriginality/aiOriginalityApi";
import {useDispatch, useSelector} from "react-redux";
import {set_storageData} from "@/store/reducer/aiOriginality/aiOriginalitySlice";

type Props = {}

const SdsrPage = ({listData, onGetParams}: Props) => {
    const dispatch = useDispatch();
    const storageData = useSelector(state => state.aiOriginality.storageData)
    const [list, setList] = useState(listData)
    const [bigMenuId, setBigMenuId] = useState(list[0]?.id)
    const [smallMenu, setSmallMenu] = useState([])
    const [smallMenuId, setSmallMenuId] = useState('')
    const [formList, setFormList] = useState([])
    const [FcSliderZSVal, setFcSliderZSVal] = useState(100)
    const [FcSliderPSVal, setFcSliderPSVal] = useState(1)
    const [isHotKeyword, setIsHotKeyword] = useState(false)
    const [hotKeywordList, setHotKeywordList] = useState([])
    const [wordsNum, setWordNum] = useState(null)
    const [params, setParams] = useState({
        vars: [],
        reqIndex: 1,
        disable: true
    })

    const [originalityStoryData, setOriginalityStoryData] = useState({})

    useEffect(() => {
        // if(list.length>0) {
        //     handleBigMenu(list[0])
        //     setTimeout(() => {
        //         handleBigMenu(list[0])
        //     },1200)
        // }

        // setTimeout(() => {
        console.log(storageData,'==========');
        if(JSON.stringify(storageData) !== '{}') {
                setOriginalityStoryData(storageData)
            console.log(originalityStoryData);
            handleBigMenu(storageData.selectBigMenuData,storageData.selectSmallMenuData)
            } else {
                if(list.length>0) {
                    handleBigMenu(list[0])
                }
            }
        // },500)


        onGetParams(params)
    }, [list]);


    const handleSetParams = () => {
        let arr = []
        let disable = formList.every(item => !(item.required && (item.value === undefined || item.value === null || item.value === '') ))

        formList.forEach(item => {
            arr.push({
                name: item.name,
                value: item.value
            })
        })
        let p = {
            vars: [...arr, {
                name: '字数',
                value: FcSliderZSVal
            }],
            articlesNum: FcSliderPSVal,
            disable: !disable
        }

        setParams(p)
        onGetParams(p)
    }

    const handleBigMenu = (val: { name?: string; id: any; list: any; },selectSmallMenuData) => {
        setBigMenuId(val.id)
        setSmallMenu(val.list)
        if(selectSmallMenuData) {
            handleSmallMenu(selectSmallMenuData)
        } else {
            handleSmallMenu(val.list[0])
        }

        let obj = {
            ...originalityStoryData,
            selectBigMenuData: val
        }
        setOriginalityStoryData(obj)
        dispatch(set_storageData(obj))
    }

    const handleSmallMenu = (val) => {
        let wordsNum = val.formList.find(item => item.label == '字数')
        // val.formList = val.formList.filter(item => item.label != '字数')
        console.log(val, '----');
        setWordNum(wordsNum)
        if (wordsNum) {
            setFcSliderZSVal(wordsNum.fieldMin * 1)
        }
        setSmallMenuId(val.id)

        console.log(originalityStoryData,'originalityStoryData====');
        // console.log(val.formList,'---');
        setFormList(val.formList)

        let obj = {
            ...originalityStoryData,
            selectSmallMenuData: val
        }
        setOriginalityStoryData(obj)
        dispatch(set_storageData(obj))
    }

    const handleChange = (val, index,formList1) => {
        console.log(val, index,formList1,formList,smallMenuId,smallMenu);
        // console.log(val, index);
        // console.log(formList);
        // 创建一个新的 formList 副本
        const newFormList = [...formList];
        // 创建新的对象副本，避免直接修改原对象
        newFormList[index] = { ...newFormList[index], value: val };

        setFormList(newFormList);
        handleSetParams()

        const newObj = {
            ...originalityStoryData,
            // 创建 selectSmallMenuData 的副本
            selectSmallMenuData: {
                ...originalityStoryData.selectSmallMenuData,
                // 用新的 formList 替换原有的 formList
                formList: newFormList
            }
        };

        setOriginalityStoryData(newObj);
        dispatch(set_storageData(newObj))
        console.log(newObj.selectSmallMenuData.formList);
    }

    const handleHotKeyword = () => {
        setIsHotKeyword(true)
    }

    const handleFcZSSlider = (val) => {
        setFcSliderZSVal(val)
        handleSetParams()
    }

    const handleFcPSSlider = (val) => {
        setFcSliderPSVal(val)
        handleSetParams()
    }

    const getColor = (val: string | number) => {
        switch (val) {
            case 0:
                return '#F8405F'
            case 1:
                return '#EE7B53'
            case 2:
                return '#FCA853'
            default:
                return 'rgba(0, 0, 0, 0.9)'
        }
        return 'index' + val + 1
    }


    // @ts-ignore
    // @ts-ignore
    // @ts-ignore
    return (
        <FcView style={styles.container}>
            <FormTitle isLeftIcon style={{paddingHorizontal: 16}} title='选版发布渠道'/>
            {/*<FcButton style={{width: 80,height: 40,lineHeight: 40,borderRadius:8}} textName={'33'}></FcButton>*/}
            {/*<FcButton type={'txtJBAndBkJB'} style={{width: 80,height: 40,lineHeight: 40}} itemStyle={{width: 80,height: 40,lineHeight: 40,borderRadius:8}} borderWidth={1} textName={'33'}></FcButton>*/}
            {/*<FcButton type={'txtJBAndBjJB'} style={{width: 80,height: 40,lineHeight: 40}} itemStyle={{width: 80,height: 40,lineHeight: 40,borderRadius:18}} ></FcButton>*/}
            <Flex wrap='wrap' style={styles.big_menu}>
                {list?.map((item, index) =>
                    <View style={styles.big_menu_item_box}>
                        <FcButton
                            key={index}
                            onClick={() => handleBigMenu(item)}
                            type={bigMenuId === item.id ? 'txtBK' : 'default'}
                            style={[styles.big_menu_item]}
                            itemStyle={{width: '100%', height: '100%'}}
                            textName={item.name} borderWidth={1}></FcButton>
                    </View>
                )}
            </Flex>
            <View style={styles.small_menu}></View>
            <Flex wrap='wrap'>
                {smallMenu?.map((item, index) =>
                    <Text  key={index} onPress={() => handleSmallMenu(item)}
                           style={[styles.small_menu_item, smallMenuId === item.id && styles.small_menu_active]}
                    >
                        {item.styleFirstCate}
                    </Text>
                    // <FcButton
                    //     key={index} onClick={() => handleSmallMenu(item)}
                    //     style={[styles.small_menu_item, smallMenuId === item.id && styles.small_menu_active]}
                    //     itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    //     textName={item.styleFirstCate}></FcButton>
                )}
            </Flex>

            <View style={{paddingHorizontal: 12}}>
                <FormTitle title='手动输入资料' isLeftIcon/>

                {formList?.map((item, index) =>
                    <>
                        {item.label != '热搜词' &&
                            <View style={styles.input_wrap} key={index}>
                                <Text style={styles.input_label}>{item.label} {item.required && <RequiredIcon/>}{item.value} :</Text>
                                <TextInput
                                    value={item.value}
                                    style={styles.input_val}
                                    placeholder={item.placeholder}
                                    placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                                    onChangeText={(text) => handleChange(text, index,formList)}
                                ></TextInput>
                            </View>
                        }
                    </>
                )}                


                {/*<View style={styles.input_wrap}>*/}
                {/*  <Text style={styles.input_label}>热搜词 :</Text>*/}
                {/*  <TextInput style={styles.input_val} placeholder='如“自填或选择抖音热点”'></TextInput>*/}
                {/*  <TouchableOpacity onPress={handleHotKeyword}>*/}
                {/*    <Text style={{ fontFamily: 'FcIconFont',fontSize: 20,color: 'black',marginLeft: 10 }}>&#xe643;</Text>*/}
                {/*  </TouchableOpacity>*/}
                {/*</View>*/}


                {wordsNum &&
                    <>
                        <FormTitle title='单篇字数'
                                   isLeftIcon
                                   style={{marginBottom: 8, marginTop: 4}}
                                   right={
                                       <View style={styles.slider_wrap}>
                                           <TextInput style={styles.slider_input}
                                                      value={FcSliderZSVal + ''}></TextInput>
                                           <Text style={styles.slider_txt}>个</Text>
                                       </View>
                                   }/>
                        <FcSlider value={FcSliderZSVal} showMinMax min={wordsNum.fieldMin * 1}
                                  max={wordsNum.fieldMax * 1} onFcSlider={handleFcZSSlider}/>
                    </>
                }

                <FormTitle title='输出篇数'
                           isLeftIcon
                           style={{marginBottom: 8, paddingTop: 32}}
                           right={
                               <View style={styles.slider_wrap}>
                                   <TextInput style={styles.slider_input} value={FcSliderPSVal + ''}></TextInput>
                                   <Text style={styles.slider_txt}>个</Text>
                               </View>
                           }/>
                <FcSlider value={FcSliderPSVal} min={1} max={10} showMinMax onFcSlider={handleFcPSSlider}/>
            </View>

            <FcModal
                isOpen={isHotKeyword}
                onFcModalClose={() => setIsHotKeyword(false)}
                titleText='抖音热搜榜'
                titleDesc='热点时间：2024-10-24 12:00'
                background={
                    <Image style={{width: '100%', height: 226}}
                           source={require('@/assets/images/public/page_bg2.png')}></Image>
                }
            >
                <View style={{paddingVertical: 8}}>
                    {hotKeywordList.map((item, index) => (
                        <TouchableOpacity key={index}>
                            <View style={styles.hotKeyword_wrap}>
                                <View style={styles.hotKeyword_left}>
                                    <Text style={[styles.hotKeyword_index, {color: getColor(index)}]}>{index + 1}</Text>
                                    <Text style={styles.hotKeyword_title} numberOfLines={1}
                                          ellipsizeMode="tail">{item.title}</Text>
                                </View>
                                <View style={styles.hotKeyword_tj}>{item.num}万</View>
                            </View>
                        </TouchableOpacity>
                    ))}
                </View>
            </FcModal>
        </FcView>
    )
}

export default SdsrPage

const styles = StyleSheet.create({
    container: {
        // flex: 1,
        // justifyContent: "center",
        // alignItems: "center",
        backgroundColor: 'white',
        borderBottomLeftRadius: 8,
        borderBottomRightRadius: 8,
        paddingBottom: 16
    },
    big_menu: {
        paddingHorizontal: 8,
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
    },
    big_menu_item_box: {
        width: '33.33%',
        height: 40,
        marginBottom: 8
    },
    big_menu_item: {
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 4,
        flex: 1,
    },
    small_menu: {
        paddingTop: 20,
        borderStyle: 'dashed',
        borderTopWidth: 1,
        borderColor: 'rgba(0, 0, 0, 0.1)',
        marginHorizontal: 12,
        marginTop: 12
    },
    small_menu_item: {
        paddingHorizontal: 9,
        paddingVertical: 5,
        borderRadius: 20,
        backgroundColor: '#F1F2F4',
        marginHorizontal: 8,
        marginBottom: 8,
        color: '#79797A',
        fontsize: 14,
    },
    small_menu_active: {
        color: '#2856FF',
        backgroundColor: 'rgba(40, 86, 255, 0.1)'
    },
    input_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        height: 56,
        borderRadius: 10,
        paddingHorizontal: 12,
        backgroundColor: '#F1F2F4',
        marginBottom: 16
    },
    input_label: {
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
        flexDirection: 'row',
        alignItems: "center",
        marginRight: 10
    },
    input_val: {
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
        flex: 1,
        height: '100%',
        borderWidth: 0, // 去掉边框
        outlineWidth: 0, // 去掉轮廓
        shadowOpacity: 0, // 去掉阴影
    },
    slider_wrap: {
        flexDirection: "row",
        alignItems: "center",
    },
    slider_input: {
        width: 56,
        height: 32,
        textAlign: "center",
        borderRadius: 8,
        backgroundColor: '#F1F2F4'
    },
    slider_txt: {
        marginLeft: 8,
        fontSize: 14,
        color: 'rgba(0,0,0,0.5)'
    },
    hotKeyword_wrap: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        height: 48,
        paddingHorizontal: 16
    },
    hotKeyword_left: {
        flexDirection: "row",
        alignItems: "center",
        flex: 1
    },
    hotKeyword_index: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)',
        marginRight: 16,
        fontWeight: 'bold'
    },
    hotKeyword_title: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    hotKeyword_tj: {
        fontSize: 12,
        color: 'rgba(0, 0, 0, 0.3)',
        marginLeft: 16
    },
})